package com.ruoyi.textbook.service.impl;

import cn.hutool.core.io.FileUtil;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.common.vo.PageResult;
import com.ruoyi.textbook.domain.Textbook;
import com.ruoyi.textbook.mapper.TextbookMapper;
import com.ruoyi.textbook.service.ITextbookService;
import com.ruoyi.textbook.vo.TextbookListVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.List;

@Slf4j
@Service
public class TextbookServiceImpl implements ITextbookService {
    @Autowired
    private TextbookMapper textbookMapper;
    @Value("${ruoyi.textbook.upload}")
    private String uploadPath;

    @Override
    public Textbook get(int textbookId) {
        return textbookMapper.getById(textbookId);
    }

    @Override
    public PageResult<Textbook> page(TextbookListVO listVO) {
        int total = textbookMapper.size(listVO);
        PageResult<Textbook> result = new PageResult<>(listVO.getPageNo() ,listVO.getPageSize() ,total);
        if(total > 0){
            List<Textbook> list = textbookMapper.list(listVO);
            result.addAll(list);
        }
        return result;
    }

    @Override
    public void update(Textbook textbook) {
        if(textbook.getId() == null){
            throw new IllegalArgumentException("textbook id cannot be null");
        }
        textbookMapper.updateTextbook(textbook);
    }

    @Override
    public Textbook add(Textbook textbook) {
        textbook.verifyComplete();

        textbook.setDefault();
        textbookMapper.addTextbook(textbook);

        return textbook;
    }

    @Override
    public Textbook upload(InputStream in ,String fileName) {
        String fn = uploadPath;
        if(!uploadPath.endsWith("/")){
            fn += "/";
        }
        fn += UUID.fastUUID().toString() + fileName;
        FileUtil.writeFromStream(in ,fn);

        Textbook textbook = new Textbook();
        textbook.setDefault();
        textbook.setName(fileName);
        textbook.setTypeDefault();
        textbook.setUri(fn);
        add(textbook);
        return textbook;
    }

    @Override
    public void del(int id) {
        Textbook textbook = get(id);
        if(textbook != null){
            textbookMapper.delTextbook(id);
            FileUtil.del(textbook.getUri());
        }

    }
}
